package ru.spb.osll.myfit.client.widget;

import ru.spb.osll.myfit.client.PageMode;
import ru.spb.osll.myfit.common.PageElement;
import ru.spb.osll.myfit.common.PageElementType;
import ru.spb.osll.myfit.common.WikiText;

import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;

public class WikiTextWidget extends PageElementWidget {

  private WikiText m_wikiText;

  private PageMode m_mode;
  
  public WikiTextWidget(GWTWidgetFactory gwtWidgetFactory, WikiText wikiText) {
    super(gwtWidgetFactory);
    m_wikiText = wikiText;
    
    sinkEvents(Event.ONMOUSEUP | Event.ONDBLCLICK | Event.ONCONTEXTMENU);
    createPopupMenu();
    initWidget(createContentWidget());
    m_mode = PageMode.EDIT;  
  }

  
  private Widget createContentWidget() {
    VerticalPanel panel = m_gwtWidgetFactory.createVerticalPanel();
    panel.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_LEFT);
    HTML html = m_gwtWidgetFactory.createHTML(m_wikiText.getHtmlText());
    panel.add(html);
    return panel;
  }


  @Override
  public PageElement save() {
    return m_wikiText;
  }

  @Override
  public void setMode(PageMode mode) {
    m_mode = mode;
  }
  
  protected void onRightClick(Event event) {
    if (!(PageMode.EDIT).equals(m_mode))
      return;
      int x = event.getClientX(); 
      int y = event.getClientY();
      m_rootPopupMenu.setPopupPosition(x, y);
      m_rootPopupMenu.show();
     
  }

  public void onBrowserEvent(Event event) {
    GWT.log("onBrowserEvent", null);
    event.preventDefault();
    switch (DOM.eventGetType(event)) {
    case Event.ONMOUSEUP:
      if (DOM.eventGetButton(event) == Event.BUTTON_LEFT) {
        GWT.log("Event.BUTTON_LEFT", null);
      }

      if (DOM.eventGetButton(event) == Event.BUTTON_RIGHT) {
        GWT.log("Event.BUTTON_RIGHT", null);
        onRightClick(event);
      }
      break;

    case Event.ONDBLCLICK:
      break;

    case Event.ONCONTEXTMENU:
      GWT.log("Event.ONCONTEXTMENU", null);
      break;

    default:
      break;
    }
  }


  @Override
  public void setOpen(boolean isOpen) {
    
  }


  @Override
  public PageElementType getType() {
    return PageElementType.WIKI_TEXT;
  }
}
